﻿Imports System.Windows.Forms
Imports TBCC.Utility

Public Class ChangePasswordForm

    Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click
        If CheckValidate() = False Then
            Exit Sub
        End If

        If CheckOldPassword() = False Then
            msg.ShowWarning("旧密码错误")
            txtOld.SelectionStart = 0
            txtOld.SelectionLength = 888
            txtOld.Focus()
            Exit Sub
        End If

        If ChangePassword() = False Then
            msg.ShowWarning("修改失败")
            Logger.Write(User.Instance.uID, User.Instance.uName, "密码修改失败", tbccLogOperateType.ChangePassword)
            Exit Sub
        End If

        Logger.Write(User.Instance.uID, User.Instance.uName, "密码修改成功", tbccLogOperateType.ChangePassword)
        msg.Show("密码修改成功。")

        Me.DialogResult = System.Windows.Forms.DialogResult.OK
        Me.Close()
    End Sub

    ''' <summary>
    ''' 取消修改
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Cancel_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Cancel_Button.Click
        Me.DialogResult = System.Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    ''' <summary>
    ''' 验证输入数据的合法性
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckValidate() As Boolean
        If Me.txtOld.Text = "" Then
            txtOld.Focus()
            Return False
        End If

        If Me.txtNew1.Text = "" Then
            txtNew1.Focus()
            Return False
        End If

        If Me.txtNew2.Text = "" Then
            txtNew2.Focus()
            Return False
        End If

        If Me.txtNew1.Text <> Me.txtNew2.Text Then
            msg.Show("两次输入的新密码不一致，请重新输入")
            txtNew2.SelectionStart = 0
            txtNew2.SelectionLength = 999
            txtNew2.Focus()
            Return False
        End If

        Return True

    End Function

    ''' <summary>
    ''' 判断输入的旧密码是否正确
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function CheckOldPassword() As Boolean
        Dim result As Boolean
        result = User.Instance.CheckOldPassword(Me.txtOld.Text)
        Return result
    End Function

    ''' <summary>
    ''' 修改密码
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ChangePassword() As Boolean
        Dim result As Boolean
        Dim oldPwd As String
        oldPwd = Me.txtOld.Text

        Dim newPwd As String
        newPwd = Me.txtNew1.Text

        result = User.Instance.ChangePassword(oldPwd, newPwd)
        Return result
    End Function

End Class
